package com.city.parking.map;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.android.bba.common.util.Util;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.city.parking.ParkingApp;
import com.city.parking.R;
import com.city.parking.util.Utils;


public class LocalOfflineMapListAdapter extends
		ArrayAdapter<OfflineMapLocalItemModel> {

	public static final int ACTION_CONFIRM_DELETE = 1;

	protected OfflineMapLocalItemModel lastActionBarItem;

	private final Context context;
	private final ArrayList<OfflineMapLocalItemModel> localListInfo;
    private ParkingApp app = null;
    private HashMap<Integer,Integer> downInfo = null;

	private Handler msgHandler;

	public LocalOfflineMapListAdapter(Context context,
			ArrayList<OfflineMapLocalItemModel> localListInfo,
			ParkingApp app, Handler activityHandler, HashMap<Integer,Integer> downInfo) {

		super(context, R.layout.offline_localmap_list, localListInfo);

		this.context = context;
		this.localListInfo = localListInfo;
        this.app = app;
		this.msgHandler = activityHandler;
        this.downInfo = downInfo;
	}

	@Override
	public int getCount() {
		return localListInfo.size();
	}

	@Override
	public OfflineMapLocalItemModel getItem(int index) {
		return localListInfo.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}


	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View rowView = null;

		if (!localListInfo.get(position).isGroupHeader) {
			final OfflineMapLocalItemModel localItem = localListInfo
					.get(position);
			rowView = inflater.inflate(R.layout.offline_localmap_list, parent,
					false);
			TextView titleView = (TextView) rowView.findViewById(R.id.title);
			titleView.setText(localItem.getCityName() + "  " + "("
                    + formatDataSize(localItem.getLocalItemInfo().serversize) + ")");

            if (ParkingApp.IS_DEBUG )
                Log.e("LocalOfflineMapListAdapter", "city is " + localItem.getCityName()
					+ "| status is " + localItem.getLocalItemInfo().status);

			LinearLayout actionButtons = (LinearLayout) rowView
					.findViewById(R.id.expanded_actions);

			if (localItem.showActionBar()) {
				actionButtons.setVisibility(View.VISIBLE);
			} else {
				actionButtons.setVisibility(View.GONE);
			}

			Button expandButton = (Button) rowView
					.findViewById(R.id.expand_button);
			TextView downloadProgress = (TextView) rowView
					.findViewById(R.id.ratio);

			Button upgrade = (Button) rowView.findViewById(R.id.upgrade);
			Button remove = (Button) rowView.findViewById(R.id.btn_delete);
			Button display = (Button) rowView.findViewById(R.id.btn_open_map);

			if (localItem.getLocalItemInfo().ratio < 100) {
				expandButton.setVisibility(View.GONE);
				downloadProgress.setVisibility(View.VISIBLE);
				upgrade.setEnabled(true);
				if (localItem.getDownloadStatus() == MKOLUpdateElement.DOWNLOADING ) {
					upgrade.setText(R.string.som_btn_pause_download);
				} else {
					upgrade.setText(R.string.som_btn_start_download);
				}

				upgrade.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
                        if (localItem.getDownloadStatus() == MKOLUpdateElement.DOWNLOADING) {
                            if (ParkingApp.IS_DEBUG )
                            	Log.d("LocalOfflineMapListAdapter", "Pause Downloading");
                            if (OfflineMapService.get() != null)
                            	OfflineMapService.get().stopOfflineMapDownload(localItem.getCityID());

						} else {
                            if (ParkingApp.network_status == ParkingApp.NO_NETWORK) {
                                Toast.makeText(context, R.string.som_network_not_connected_error,
                                     Toast.LENGTH_SHORT).show();
                            } else {
                                if (ParkingApp.IS_DEBUG )
                                	Log.d("LocalOfflineMapListAdapter", "Start Downloading");
                                //offlineMapManager.start(localItem.getCityID());
                                if (OfflineMapService.get() != null) {
                                	OfflineMapService.get().startOfflineMapDownload(localItem.getCityID());
                                	downInfo.put(localItem.getCityID(), MKOLUpdateElement.DOWNLOADING);
                                } else {
                                	Log.d("LocalOfflineMapListAdapter", "Start Downloading Fialed");
                                }
                                //upgrade.setText(R.string.som_btn_pause_download);
                            }
						}
						notifyDataSetChanged();
					}
				});
			} else {
				expandButton.setVisibility(View.VISIBLE);
				downloadProgress.setVisibility(View.GONE);
				upgrade.setText(R.string.som_btn_upgrade_map);
				if (localItem.getLocalItemInfo().update) {
					// update.setText(context.getResources().getString(
					// R.string.som_text_map_update_available));
					upgrade.setEnabled(true);
                    expandButton.setText(R.string.som_text_map_update_available);
                    expandButton.setTextColor(context.getResources().getColor(R.color.red));
				} else {
					// update.setText(context.getResources().getString(
					// R.string.som_text_map_latest_version));
					upgrade.setEnabled(false);
                    expandButton.setText(R.string.som_btn_downloaded);
                    expandButton.setTextColor(context.getResources().getColor(R.color.black));
				}

				upgrade.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
                        if (ParkingApp.network_status == ParkingApp.NO_NETWORK) {
                            Toast.makeText(context, R.string.som_network_not_connected_error,
                                Toast.LENGTH_SHORT).show();
                        } else {                            
                            app.mOffline.remove(localItem.getCityID());
                            if (OfflineMapService.get() != null)
                            	OfflineMapService.get().startOfflineMapDownload(localItem.getCityID());
                        }
					}
				});
			}

			// TextView update = (TextView) rowView.findViewById(R.id.update);
			TextView ratio = (TextView) rowView.findViewById(R.id.ratio);
			ratio.setText(localItem.getLocalItemInfo().ratio + "%");

			remove.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// send msg to main UI to display dislog
					Message msg = msgHandler.obtainMessage();
					msg.what = ACTION_CONFIRM_DELETE;
					Bundle msgData = new Bundle();
					msgData.putInt("city_id",
							localItem.getLocalItemInfo().cityID);
					msg.setData(msgData);
					msgHandler.sendMessage(msg);
				}
			});

			display.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Utils.log("display.setOnClickListener");
					Intent intent = new Intent();
					intent.putExtra("x",
							localItem.getLocalItemInfo().geoPt.longitude);
					intent.putExtra("y",
							localItem.getLocalItemInfo().geoPt.latitude);
					intent.setClass(context, BaseMapActivity.class);
					context.startActivity(intent);
				}
			});

			Button expandImage = (Button) rowView.findViewById(R.id.expand_img);
			OnClickListener mExpandClickListener = (new OnClickListener() {
				@Override
				public void onClick(View v) {

					if (localItem.showActionBar() == true) {
						localItem.setActionBar(false);
					} else {
						if (lastActionBarItem != null) {
							lastActionBarItem.setActionBar(false);
						}
						localItem.setActionBar(true);
						lastActionBarItem = localItem;
					}
					notifyDataSetChanged();
				}
			});

			downloadProgress.setOnClickListener(mExpandClickListener);
			expandButton.setOnClickListener(mExpandClickListener);
			expandImage.setOnClickListener(mExpandClickListener);

		} else {
			rowView = inflater.inflate(R.layout.offline_map_group_header_item,
					parent, false);
			TextView titleView = (TextView) rowView
					.findViewById(R.id.group_header);
			titleView.setText(localListInfo.get(position).getHeaderName());
		}

		return rowView;
	}

	public String formatDataSize(int size) {
		String ret = "";
		if (size < (1024 * 1024)) {
			ret = String.format("%dK", size / 1024);
		} else {
			ret = String.format("%.1fM", size / (1024 * 1024.0));
		}
		return ret;
	}
}
